package server.resolver.resource;

import server.response.ResponseHeader;
import server.constant.HttpStatusCode;
import server.response.HttpResponse;

import java.io.*;
import java.nio.file.Files;

/**
 * @author cg
 * @date 2023/6/7 14:12
 */
public class DefaultResourceResolver implements ResourceResolver {
    //单例模式
    private volatile static DefaultResourceResolver instance;

    private void HtmlResolver() {
    }

    public static DefaultResourceResolver getInstance() {
        if (instance == null) {
            synchronized (DefaultResourceResolver.class) {
                if (instance == null) {
                    instance = new DefaultResourceResolver();
                }
            }
        }
        return instance;
    }

    @Override
    public void resolve(File file, HttpResponse httpResponse, String contentType) throws IOException {
        InputStream inputStream = Files.newInputStream(file.toPath());
        int len = 0;
        long start = System.currentTimeMillis();
        while (len == 0) {
            len = inputStream.available();
            long end = System.currentTimeMillis();
            if (end - start > 1000 * 10) return;
        }
        //先写入请求头
        ResponseHeader responseHeader = new ResponseHeader.Builder()
                .statusCode(HttpStatusCode.SUCCESS)
                .contentType(contentType)
                .contentLength(String.valueOf(len))
                .build();

        httpResponse.write(responseHeader.toString());
        OutputStream outputStream = httpResponse.getOutputStream();

        byte[] bytes = new byte[bufferSize];
        while ((len = inputStream.read(bytes)) != -1) {
            //每次读取的数据都实时写入response中
            if (len < bufferSize) {
                for (int i = 0; i < len; i++) {
                    outputStream.write(bytes[i]);
                }
            } else {
                outputStream.write(bytes);
            }
        }
        inputStream.close();
        httpResponse.flush();
    }
}
